package my.merborn.ordersysteam105.controllers;

import my.merborn.ordersysteam105.models.dao.UserMapper;
import my.merborn.ordersysteam105.models.pojo.User;
import my.merborn.ordersysteam105.models.pojo.enums.Power;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebFilter(filterName = "backgroundfilter",urlPatterns ="/background.html")
public class BackGroundFilter implements Filter {

    @Resource
    UserMapper um;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("background filter start");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //System.out.println("request catched by background.html");
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Integer uid = null;
        HttpSession session = req.getSession();
     try{
      uid = (Integer) session.getAttribute("uid");
     }catch (Exception e){
         resp.sendRedirect("userlogin.html");
     }

        if (uid == null) {
            resp.sendRedirect("userlogin.html");
        } else {
            User user = um.selectByPrimaryKey(uid);
            if (Power.ADMIN.getPower().equals(user.getuPower())) {
                chain.doFilter(req, resp);
            } else {
                resp.sendRedirect("userlogin.html");
            }
        }
    }

    @Override
    public void destroy() {
        System.out.println("warn ! + background filter is destoryed,if you turn off the server,please miss this message");
    }
}
